package nl.ypmits.utils.as3.log {
	import caurina.transitions.Tweener;

	import nl.ypmits.utils.as3.bitmap.BitmapConverter;
	import nl.ypmits.utils.as3.stage.SimpleStage;
	import nl.ypmits.utils.as3.view.scrollbar.ScrollBar;
	import nl.ypmits.utils.as3.view.scrollbar.event.ScrollBarEvent;
	import nl.ypmits.utils.as3.view.scrollbar.input.ScrollBarInput;

	import flash.display.Bitmap;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;

	/**
	 * @author davelenz
	 */
	public class ScrollBarWrapper extends Sprite {
		private var starty : Number;

		public function ScrollBarWrapper( target : DisplayObjectContainer, _height : Number, _mousewheel : Boolean = true, _convertToBitmap : Boolean = false ) 
		{
			x = target.x;
			y = starty = target.y;
			
			if( _convertToBitmap ) 
			{
				var snapshot : Bitmap = BitmapConverter.convertToBitmap( target, true );
				var length : int = target.numChildren;
				for (var i : int = 0; i < length; i++) {
					target.removeChildAt( 0 );
				}
				target.addChild( snapshot );
			}
			
			if( target.height > _height ) 
			{
				var barwidth : int = 6;
				var trackwidth : int = 6;
				var extraflesh : int = 6;
				
				var scrubber : Sprite = new Sprite( );
				scrubber.graphics.beginFill( 0x666666, 1 );
				scrubber.graphics.drawRect( 0, 0, barwidth, 100 );
				scrubber.graphics.beginFill( 0xFF9900, 0 );
				scrubber.graphics.drawRect( -extraflesh, 0, barwidth + ( extraflesh * 2 ), 100 );
				scrubber.graphics.endFill( );
				scrubber.buttonMode = true;
				
				var scrolltrack : Sprite = new Sprite( );
				scrolltrack.graphics.beginFill( 0x666666, .4 );
				scrolltrack.graphics.drawRect( 0, 0, trackwidth, _height );
				scrolltrack.graphics.endFill( );
				
				var input : ScrollBarInput = new ScrollBarInput( );
				input.scrubber = scrubber;
				input.scrolltrack = scrolltrack;
				input.toscroll = target;
				input.stage = SimpleStage.instance.getStage();
				input.height = _height;
				input.setupGradients( true, true, 10 );
				input.xoffset = 8;
				input.topBottomGradient = false;
				input.topBottomGradientOutside = false;
				input.topBottomGradientOutsideFactor = 15;
				
				var scrollbar : ScrollBar = new ScrollBar( input, _mousewheel );
				scrollbar.addEventListener( ScrollBarEvent.SCROLL_UPDATE, handlerFunction );
				addChild( scrollbar );
			}
		}

		
		private function handlerFunction( e : ScrollBarEvent ) : void 
		{
			var diff : Number = e.flesh * e.pct;
			Tweener.addTween( e.toscroll, {y:starty-diff, time:.4, ease:"easeOutCubic"} );
		}
	}
}
